package com.fruit.auth.web.action;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fruit.auth.model.Role;
import com.fruit.auth.model.User;
import com.fruit.auth.service.RoleService;
import com.fruit.auth.service.UserService;
import com.fruit.system.model.NavMenuVO;
import com.fruit.system.service.MenuService;
import com.fruit.util.Algorithm;
import com.fruit.util.SecurityUtil;
import com.fruit.web.action.util.BaseAction;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User>
{

	private User user;
	private static final long serialVersionUID = 3906185454836277106L;
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="roleService")
	private RoleService roleService;
	
	@Resource(name="menuService")
	private MenuService menuService;
	
	private String userIds;
	private String roleIds;
	
	public void setUserIds(String userIds)
	{
		this.userIds = userIds;
	}
	public void setRoleIds(String roleIds)
	{
		this.roleIds = roleIds;
	}


	/**
	 * 获取用户有权访问的所有菜单
	 * @return
	 */
	public String menus()
	{
		User user=(User) getSession().getAttribute("user");
		List<NavMenuVO> authMenus= menuService.findMenusForUser(user);
		renderJson(authMenus);
		return NONE;
	}


	@Override
	public void prepare() throws Exception
	{
		user=new User();
	}

	@Override
	public User getModel()
	{
		return user;
	}
	
	public String saveOrUpdate()
	{
		if(user.getId()==null)
		{
			user.setPassword(SecurityUtil.messageDigest("123456", Algorithm.SHA_256));
		}
		userService.saveOrUpdateEntity(user);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String deletes()
	{
		userService.deleteUsers(userIds);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String findRoles()
	{
		List<Role> authedRoles=userService.findUserRoles(user);
		List<Role> unauthedRoles=roleService.findAllEntity();
		unauthedRoles.removeAll(authedRoles);
		Map<String,List<Role>> data=new HashMap<String,List<Role>>();
		data.put("authedRoleList", authedRoles);
		data.put("unauthedRoleList", unauthedRoles);
		renderJson(data);
		return NONE;
	}
	
	public String authUserRoles()
	{
		List<Serializable> ids=new ArrayList<Serializable>();
		if(!roleIds.equals(""))
		{
			String[] _ids=roleIds.split(",");
			for(String _id:_ids)
			{
				ids.add(Integer.parseInt(_id));
			}
		}
		userService.updateUserRoles(user, ids);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
}
